package cn.gzjp.modules.dt.api.web;

import cn.gzjp.common.web.BaseController;
import cn.gzjp.modules.dt.api.bean.ExamQuestionVo;
import cn.gzjp.modules.dt.entity.DtUser;
import cn.gzjp.modules.dt.entity.Exam;
import cn.gzjp.modules.dt.entity.Question;
import cn.gzjp.modules.dt.entity.TestRecord;
import cn.gzjp.modules.dt.service.DtUserService;
import cn.gzjp.modules.dt.service.ExamService;
import cn.gzjp.modules.dt.service.QuestionService;
import cn.gzjp.modules.dt.service.TestRecordService;
import cn.gzjp.modules.it.api.bean.CommonJson;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @Author zengcp
 * @Date 2018/2/24
 */

/**
 * 考试管理
 */
@RestController("driveExam")
@Api(value = "考试模式", description = "考试模式")
@RequestMapping(value = "${frontPath}/exam")
public class DriveExamController extends BaseController {

    @Autowired
    private QuestionService questionService;
    @Autowired
    private ExamService examService;
    @Autowired
    private DtUserService dtUserService;



    /**
     * 开始考试
     */
    @ApiOperation(value = "开始考试")
    @RequestMapping(value = "start", method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(name="openid",value="openid",dataType="String",paramType="query",required =true)
    })
    public String start(String openid) {
        log.info("开始考试 openid="+openid);
        CommonJson result = new CommonJson();
        if (StringUtils.isBlank(openid)||openid.length()<12) {
            result.setMsg("openid不能为空");
            result.setCode(1);
            log.info(mapper.toJson(result));
            return this.mapper.toJson(result);
        }

        DtUser user = dtUserService.get(openid);
        if(user==null){
            user = new DtUser();
            user.setId(openid);
            dtUserService.save(user);
        }

        List<Exam>  exams =  examService.createExamPaper(openid);//创建试卷
        //用户数据归零
        user.setExamSn(1);//从1开始
        user.setExamScore(0);
        user.setExamCorrectCount(0);
        user.setExamCount(0);
        dtUserService.save(user);//重新开始

        log.info(openid+":开始获取第"+user.getExamSn()+"题目");
        Exam exam =  examService.findByOpenidAndSn(openid,user.getExamSn());
        if(exam==null){
            result.setCode(-1);
            result.setMsg("题目不存在");
        }
        exam = examService.get(exam.getId());
        ExamQuestionVo data = new ExamQuestionVo();
        Question question= exam.getQuestion();
        question = questionService.get(question.getQuestionId());
        question.setSn(exam.getSn());
        data.setQuestion(question);
        data.setMaxSn(exams.size());//100题目
        data.setCorrectCount(user.getExamCorrectCount());
        data.setTotalCount(user.getExamCount());
        result.setData(data);
        log.info("返回数据="+mapper.toJson(result));
        return this.mapper.toJson(result);
    }



    /**
     * 考试题目获取
     */
    @ApiOperation(value = "题目获取")
    @RequestMapping(value = "question", method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(name="openid",value="openid",dataType="String",paramType="query",required =true),
            @ApiImplicitParam(name="sn",value="题目序号",dataType="Integer",paramType="query",required =true)
    })
    public String question(String openid,Integer sn) {
        log.info("考试题目获取 openid="+openid+"|sn="+sn);
        CommonJson result = new CommonJson();
        if (StringUtils.isBlank(openid)||openid.length()<12) {
            result.setMsg("openid不能为空");
            result.setCode(1);
            log.info(mapper.toJson(result));
            return this.mapper.toJson(result);
        }
        if(sn<=0||sn>100){
            result.setMsg("题目已做完,答题结束");
            result.setCode(2);
            log.info(mapper.toJson(result));
            return this.mapper.toJson(result);
        }
        DtUser user = dtUserService.get(openid);
        if(user==null){
            user = new DtUser();
            user.setId(openid);
            dtUserService.save(user);
        }
        Exam examSearch = new Exam();
        examSearch.setOpenid(openid);
        List<Exam> exams =  examService.findList(examSearch);
        if(exams==null||exams.size()==0||user.getExamSn()==100){
            examService.createExamPaper(openid);//创建试卷
            user.setExamSn(1);//从1开始
            user.setExamScore(0);
            user.setExamCorrectCount(0);
            user.setExamCount(0);
            dtUserService.save(user);//重新开始
        }


        Exam exam = examService.findByOpenidAndSn(openid,sn);
        if(exam==null){
            result.setCode(-1);
            result.setMsg("题目不存在");
        }
        exam = examService.get(exam.getId());
        ExamQuestionVo data = new ExamQuestionVo();
        Question question= exam.getQuestion();
        question = questionService.get(question.getQuestionId());
        question.setSn(exam.getSn());
        data.setMaxSn(exams.size());//100题目
        data.setQuestion(question);
        data.setCorrectCount(user.getExamCorrectCount());
        data.setTotalCount(user.getExamCount());
        result.setData(data);
        log.info("返回数据="+mapper.toJson(result));
        return this.mapper.toJson(result);
    }

    /**
     * 答题
     * @param openid
     * @param sn
     * @param option
     * @return
     */
    @ApiOperation(value = "答题")
    @RequestMapping(value = "answer", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name="openid",value="openid",dataType="String",paramType="form",required =true),
            @ApiImplicitParam(name="sn",value="题目序号",dataType="Integer",paramType="form",required =true),
            @ApiImplicitParam(name="option",value="答案选项",dataType="String",paramType="form",required =true),
    })
    public String answer(String openid, Integer sn, String option) {
        log.info("考试答题 openid="+openid+"|sn="+sn+"|option="+option);
        CommonJson result = new CommonJson();
        DtUser user = dtUserService.get(openid);
        if (StringUtils.isBlank(openid)||openid.length()<12) {
            result.setMsg("openid不能为空");
            result.setCode(1);
            log.info(mapper.toJson(result));
            return this.mapper.toJson(result);
        }
        if(user==null){
            user = new DtUser();
            user.setId(openid);
            dtUserService.save(user);
        }
        Exam exam = examService.findByOpenidAndSn(openid,sn);
        if(exam==null){
            result.setCode(-1);
            result.setMsg("题目不存在");
        }

        exam = examService.get(exam.getId());
        Question question= exam.getQuestion();
        question = questionService.get(question.getQuestionId());
        option = option.replaceAll(",", "");
        char[] chars = option.toString().toCharArray();
        Arrays.sort(chars);
        String newAnswer = new String(chars);
        exam.setAnswer(newAnswer);
        exam.setResult("1");
        exam.setAnswerTime(new Date());
        if(question.getAnswer().equals(newAnswer)){
            exam.setResult("0");
            result.setMsg("恭喜你,答对了！");
            user.setExamCorrectCount(user.getExamCorrectCount()+1);
            user.setExamScore(user.getExamScore()+1);
        }else {
            result.setCode(1);
            result.setMsg("很遗憾,答错了");
        }
        examService.save(exam);
        user.setExamCount(user.getExamCount()+1);
        user.setExamSn(sn);
        //dtUserService.save(user);不做更新了，统一交卷更新
        result.setData(sn);
        log.info("返回数据="+mapper.toJson(result));
        return this.mapper.toJson(result);
    }

    /**
     * 答题
     * @param openid
     * @return
     */
    @ApiOperation(value = "交卷")
    @RequestMapping(value = "submit", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name="openid",value="openid",dataType="String",paramType="form",required =true)
    })
    public String submit(String openid) {
        log.info("考试交卷 openid="+openid);
        CommonJson result = new CommonJson();
        DtUser user = dtUserService.get(openid);
        if (StringUtils.isBlank(openid)||openid.length()<12) {
            result.setMsg("openid不能为空");
            result.setCode(1);
            log.info(mapper.toJson(result));
            return this.mapper.toJson(result);
        }
        if(user==null){
            user = new DtUser();
            user.setId(openid);
            dtUserService.save(user);
        }
        user.setExamCorrectCount(examService.getCorrectCount(openid));
        user.setExamScore(examService.getCorrectCount(openid));
        user.setExamCount(examService.getTotalCount(openid));
        dtUserService.save(user);
        result.setData(user);
        log.info("返回数据="+mapper.toJson(result));
        return this.mapper.toJson(result);
    }


    /**
     * 我的错题
     */
    @ApiOperation(value = "我的错题")
    @RequestMapping(value = "wdct", method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(name="openid",value="openid",dataType="String",paramType="query",required =true)
    })
    public String wdct(String openid) {
        log.info("我的错题获取 openid="+openid);
        CommonJson result = new CommonJson();
        if (StringUtils.isBlank(openid)||openid.length()<12) {
            result.setMsg("openid不能为空");
            result.setCode(1);
            log.info(mapper.toJson(result));
            return this.mapper.toJson(result);
        }
        Exam search = new Exam();
        search.setOpenid(openid);
        search.setResult("1");
        List<Exam> uncorrectList = examService.findList(search);
        result.setData(uncorrectList);
        log.info("返回数据="+mapper.toJson(result));
        return this.mapper.toJson(result);
    }

    /**
     * 我的答题
     */
    @ApiOperation(value = "我的答题")
    @RequestMapping(value = "wddt", method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(name="openid",value="openid",dataType="String",paramType="query",required =true)
    })
    public String wddt(String openid) {
        log.info("我的答获取 openid="+openid);
        CommonJson result = new CommonJson();
        if (StringUtils.isBlank(openid)||openid.length()<12) {
            result.setMsg("openid不能为空");
            result.setCode(1);
            log.info(mapper.toJson(result));
            return this.mapper.toJson(result);
        }
        Exam search = new Exam();
        search.setOpenid(openid);
        List<Exam> uncorrectList = examService.findList(search);
        result.setData(uncorrectList);
        log.info("返回数据="+mapper.toJson(result));
        return this.mapper.toJson(result);
    }

    /**
     * 排行榜
     */
    @ApiOperation(value = "排行榜")
    @RequestMapping(value = "ranking", method = RequestMethod.GET)
    public String ranking() {
        log.info("排行榜");
        CommonJson result = new CommonJson();
        List<DtUser> users = dtUserService.findList(new DtUser());
        result.setData(users);
        log.info("返回数据="+mapper.toJson(result));
        return this.mapper.toJson(result);
    }


}
